<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
  <style>
    table {
      width: 100%;
      border-collapse: collapse;
    }

    th,
    td {
      border: 1px solid #ddd;
      padding: 8px;
    }

    th {
      position: sticky;
      top: 0;
      z-index: 1;
      background-color: #f2f2f2;
    }

    .footer {
      width: 100%;
      height: 50px;
      background: linear-gradient(to right, #f0ecf4, #b5c2d7);
      display: flex;
      align-items: center;
      justify-content: center;
      position: fixed;
      bottom: 0;
      z-index: 2;
    }

    body {
      padding-bottom: 70px;
      /* 确保内容不会被底部栏遮挡 */
    }

    .pagination {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }

    .pagination button,
    .pagination input {
      margin: 0 5px;
      padding: 5px 10px;
      cursor: pointer;
      border: 1px solid #dcdfe6;
      background-color: #fff;
      color: #606266;
      outline: none;
    }

    .pagination button:hover {
      color: #409eff;
    }

    .pagination button.active {
      background-color: #409eff;
      color: #fff;
    }

    .pagination input {
      width: 50px;
      text-align: center;
    }
  </style>
</head>

<body>
  <div
    style="display: flex;flex-direction: row;justify-content: space-evenly;align-items: center;background:linear-gradient(to right, #f0ecf4, #b5c2d7)">
    <h1
      style="font-size: 20px;font-weight: normal;border: 1px solid blue;background-color: rgb(130, 130, 234);padding: 15px;">
      扫描信息</h1>
    <select id="scan-type" style="margin-left: 10px; padding: 5px;">
      <option value="1">收件扫描</option>
      <option value="2">入仓扫描</option>
      <option value="3">装车发件扫描</option>
      <option value="4">收入发扫描</option>
      <option value="5">到件扫描</option>
      <option value="6">派件扫描</option>
      <option value="7">签收扫描</option>
    </select>
    <button id="import-button"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #fff; color: #606266; cursor: pointer; outline: none;">导入单号</button>

    <button id="confirm-button"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #fff; color: #606266; cursor: pointer; outline: none;">开始操作</button>

  </div>
  <div id="drawer-modal"
    style="display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 80%; max-width: 600px; background-color: white; padding: 20px; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);">
    <textarea id="import-textarea" placeholder="单号一行一个输入" style="width: 100%; height: 200px; resize: none;"></textarea>
    <div id="line-count" style="text-align: right; margin-top: 5px; color: #606266;">当前行数: 0</div>
    <div style="display: flex; justify-content: flex-end; margin-top: 10px;">
      <button id="cancel-import-button"
        style="margin-right: 10px; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #fff; color: #606266; cursor: pointer; outline: none;">取消</button>
      <button id="confirm-import-button"
        style="padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #fff; color: #606266; cursor: pointer; outline: none;">确认</button>
    </div>
  </div>
  <table id="data-table">
    <thead>
      <tr>
        <th>序号</th>
        <th>运单号</th>
        <th>重量（kg）</th>
        <th>长度（mm）</th>
        <th>宽度（mm）</th>
        <th>高度（mm）</th>
        <th>体积（m³）</th>
        <th>扫描时间</th>
        <th>状态</th>
      </tr>
    </thead>
    <tbody>
    </tbody>
  </table>
  <div class="pagination" id="pagination">
    <!-- 页码按钮将在这里动态生成 -->
  </div>
  <div class="search-container" style="text-align: center; margin-top: 30px;">
    <input type="text" id="search-input" placeholder="输入运单号"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; outline: none;">
    <button id="search-button"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #fff; color: #606266; cursor: pointer; outline: none;">查询</button>

  </div>
  <div id="mode-info"></div>
  <!-- <div>
    <button id="switchMode-button"
      style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #573333; color: #e7ebf3; cursor: pointer; outline: none;">切换上传</button>
    <h3 style="display: inline-block;">当前为：<h3 style="display: inline-block;" id="switchMode">Loading...</h3></h3>
  </div> -->
  <!-- <button id="switch-button"
    style="display: inline-block; padding: 5px 10px; border: 1px solid #dcdfe6; background-color: #a3130c; color: white; cursor: pointer; outline: none;">点击切换流水线状态</button> -->
  <div class="results-container" id="results-container">
    <!-- 查询结果将显示在这里 -->
  </div>
  <script>
    let ws;
    let currentPage = 1;
    let totalPages = 1;
    const limit = 10; // 每页显示的记录数
    let totalList = 0
    let showData = false
    let Infomation = ''
    let mode = 1
    let taskCode = ''
    expressList = []
    function startWebSocket() {
      ws = new WebSocket('ws://127.0.0.1:3000');

      ws.onopen = () => {
        console.log('WebSocket connection established');
      };

      ws.onmessage = (event) => {
        if (event.data === 'ping') {
          ws.send(JSON.stringify({ info: 'pong' }));
          return;
        }
        if (event.data === 'logMessage') {
          fetchLogs(currentPage)
          fetchFailLogs()
        }
      };

      ws.onclose = () => {
        console.log('WebSocket connection closed');
        setTimeout(startWebSocket, 2000);
      };

      ws.onerror = (error) => {
        console.error('WebSocket error:', error);
        setTimeout(startWebSocket, 2000);
      };
    }

    function fetchLogs(page) {
      fetch(`http://localhost:3001/logs?page=${page}&limit=${limit}`)
        .then(response => response.json())
        .then(data => {
          totalList = data.total
          showData = data.results.some(log => log.mapData.volume !== undefined && log.mapData.volume !== null && log.mapData.volume !== ''); // 检查是否有记录包含体积数据
          renderTable(data.results);
          totalPages = Math.ceil(data.total / limit);
          createPagination();

        })
        .catch(error => console.error('Error fetching logs:', error));
    }
    function fetchFailLogs(page) {
      fetch(`http://localhost:3001/failLogs`)
        .then(response => response.json())
        .then(data => {
          if (data.total == 0) {
            alert('全部上传成功！')
          } else {
            alert('上传失败单号总数' + data.total + "条");
            console.log(data.results, '失败的条数');

            // // 创建一个按钮元素
            // const copyButton = document.createElement('button');
            // copyButton.innerText = '复制失败单号';

            // // 为按钮添加点击事件监听器
            // copyButton.addEventListener('click', () => {
            //   // 将 data.results 数组中的每个值拼接成一个字符串
            //   const failedNumbers = data.results.join('\n');

            //   // 创建一个临时的 textarea 元素来复制文本到剪贴板
            //   const textarea = document.createElement('textarea');
            //   textarea.value = failedNumbers;
            //   document.body.appendChild(textarea);
            //   textarea.select();
            //   document.execCommand('copy');
            //   document.body.removeChild(textarea);

            //   alert('失败单号已复制到剪贴板');
            // });

            // // 将按钮添加到页面中
            // document.body.appendChild(copyButton);
          }
        })
        .catch(error => console.error('Error fetching logs:', error));
    }

    function fetchdeleteLogs(page) {
      fetch(`http://localhost:3001/deleteAllLogs`)
        .then(response => response.json())
        .then(() => {
          // uploadExpress(mode)

          // 分批次
      if(expressList.length>2000){
        const chunkSize = 1000; // 每块1000条数据
        const totalChunks = Math.ceil(expressList.length / chunkSize);

        processAllData();
        async function processAllData() {
        // 处理块，100条
        for (let i = 0; i < totalChunks; i++) {
            const start = i * chunkSize;
            const end = start + chunkSize;
            const chunk = expressList.slice(start, end);
            await uploadExpress(mode,chunk);//1
        }
        }
      }else{
        uploadExpress(mode,expressList)
      }

          // 所有批次上传完成后执行以下操作
          alert('本次数据传输完毕,共' + expressList.length + "条");
        })
        .catch(error => console.error('Error fetching logs:', error));
    }


    async function getInfomation() {
      const res = await fetch(`http://localhost:3001/JtLog/Infomation`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const data = await res.json();
      if (data.code === 200) {
        Infomation = data.info
        document.getElementById('additional-info').innerText = Infomation.networkName + `(${Infomation.networkCode})-` + Infomation.name + `(${Infomation.staffNo})-永久使用`;
      } else {
        document.getElementById('additional-info').innerText = `当前未登录或未授权`;
      }
    }

    async function uploadExpress(cmode,expressList) {
      let urlFetch = `http://localhost:3001/JtLog/upload`
      await fetch(urlFetch, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          mode: cmode,
          data: expressList
        })
      });
    }


    function renderTable(logs) {
      const tableBody = document.querySelector('#data-table tbody');
      tableBody.innerHTML = '';

      const tableHead = document.querySelector('#data-table thead tr');
      if (showData) {
        tableHead.innerHTML = `
      <th>序号</th>   
      <th>运单号</th>
      <th>重量（kg）</th>
      <th>长度（mm）</th>
      <th>宽度（mm）</th>
      <th>高度（mm）</th>
      <th>体积（m³）</th>
      <th>扫描时间</th>
      <th>状态</th>
    `;
      } else {
        tableHead.innerHTML = `
      <th>序号</th>   
      <th>运单号</th>
      <th>重量（kg）</th>
      <th>扫描时间</th>
      <th>状态</th>
    `;
      }

      logs.forEach((log, index) => {
        const row = document.createElement('tr');
        if (showData) {
          row.innerHTML = `
        <td>${((currentPage - 1) * limit) + index + 1}</td>
        <td>${JSON.parse(log.mapData).code}</td>
        <td>${JSON.parse(log.mapData).weight}</td>
        <td>${JSON.parse(log.mapData).length}</td>
        <td>${JSON.parse(log.mapData).width}</td>
        <td>${JSON.parse(log.mapData).height}</td>
        <td>${JSON.parse(log.mapData).volume}</td>
        <td>${log.formattedTime}</td>
        <td>${log.response}</td>
      `;
        } else {
          row.innerHTML = `
        <td>${((currentPage - 1) * limit) + index + 1}</td>
        <td>${JSON.parse(log.mapData).code}</td>
        <td>${JSON.parse(log.mapData).weight}</td>
        <td>${log.formattedTime}</td>
        <td>${log.response}</td>
      `;
        }

        tableBody.appendChild(row);
      });
    }

    function createPagination() {
      const pagination = document.getElementById('pagination');
      pagination.innerHTML = '';

      const maxVisiblePages = 3; // 最多显示的页码数
      const halfMaxVisiblePages = Math.floor(maxVisiblePages / 2);

      let startPage = Math.max(1, currentPage - halfMaxVisiblePages);
      let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
      startPage = Math.max(1, endPage - maxVisiblePages + 1);

      for (let i = startPage; i <= endPage; i++) {
        const button = document.createElement('button');
        button.textContent = i;
        button.classList.add('page-button');
        if (i === currentPage) {
          button.classList.add('active');
        }
        button.addEventListener('click', () => {
          currentPage = i;
          fetchLogs(currentPage);
        });
        pagination.appendChild(button);
      }

      if (startPage > 1) {
        const ellipsis = document.createElement('span');
        ellipsis.textContent = '...';
        pagination.insertBefore(ellipsis, pagination.firstChild);
      }

      if (endPage < totalPages) {
        const ellipsis = document.createElement('span');
        ellipsis.textContent = '...';
        pagination.appendChild(ellipsis);
      }

      const gotoInput = document.createElement('input');
      gotoInput.type = 'number';
      gotoInput.min = 1;
      gotoInput.max = totalPages;
      gotoInput.placeholder = 'Go to';
      gotoInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter') {
          const gotoPage = parseInt(gotoInput.value, 10);
          if (!isNaN(gotoPage) && gotoPage >= 1 && gotoPage <= totalPages) {
            currentPage = gotoPage;
            fetchLogs(currentPage);
          }
        }
      });
      pagination.appendChild(gotoInput);
    }

    function displayResults(logs) {
      const resultsContainer = document.getElementById('results-container');
      resultsContainer.innerHTML = ''; // 清空之前的查询结果

      if (logs.length === 0) {
        resultsContainer.innerHTML = '<h2>没有找到匹配的日志</h2>';
        return;
      }

      const ul = document.createElement('ul');
      logs.forEach(log => {
        const li = document.createElement('li');
        li.innerHTML = `
                    <strong>运单号:</strong> ${log.mapData.code}<br>
                    <strong>响应:</strong> ${log.response}<br>
                    <strong>时间:</strong> ${log.formattedTime}
                `;
        ul.appendChild(li);
      });

      resultsContainer.appendChild(ul);
    }
    startWebSocket();
    fetchLogs(currentPage); // 初始加载第一页数据

    getInfomation()
    document.getElementById('mode-info').innerText = '当前扫描模式为：' + "收件扫描"
    document.getElementById('search-button').addEventListener('click', () => {
      const searchCode = document.getElementById('search-input').value.trim();
      if (searchCode) {
        fetch(`http://localhost:3001/logs/selectLog?code=${searchCode}`)
          .then(response => response.json())
          .then(data => {
            displayResults(data.logs);
          })
          .catch(error => console.error('Error fetching logs:', error));
      } else {
        alert('请输入运单号');
      }
    });

    document.getElementById('import-button').addEventListener('click', () => {
      document.getElementById('drawer-modal').style.display = 'block';
    });

    document.getElementById('cancel-import-button').addEventListener('click', () => {
      document.getElementById('drawer-modal').style.display = 'none';
    });

    document.getElementById('confirm-import-button').addEventListener('click', () => {
      const importText = document.getElementById('import-textarea').value;
      const trackingNumbers = importText.split('\n').filter(line => line.trim() !== '');
      console.log(trackingNumbers);
      alert(`本次导入数据共 ${trackingNumbers.length} 条`);
      document.getElementById('drawer-modal').style.display = 'none';
    });

    document.getElementById('import-textarea').addEventListener('input', () => {
      expressList = []
      const importText = document.getElementById('import-textarea').value;
      expressList = importText.split('\n').filter(line => line.trim() !== '')
      const lineCount = importText.split('\n').length;
      document.getElementById('line-count').innerText = `当前行数: ${lineCount}`;
    });
    document.getElementById('confirm-button').addEventListener('click', async () => {
      // 每次操作前先删掉数据库所有的数据
      fetchdeleteLogs()

    });
    document.getElementById('scan-type').addEventListener('change', (event) => {
      const selectedValue = event.target.value;
      mode = selectedValue
      if (mode == 1) {
        document.getElementById('mode-info').innerText = '当前扫描模式为：' + "收件扫描"
      }
      if (mode == 2) {
        document.getElementById('mode-info').innerText = '当前扫描模式为：' + "入仓扫描"
      }
      if (mode == 3) {
        document.getElementById('mode-info').innerText = '当前扫描模式为：' + "装车发件扫描"
      }
      if (mode == 4) {
        document.getElementById('mode-info').innerText = '当前扫描模式为：' + "收入发扫描"
      }
      if (mode == 5) {
        // 使用 prompt 弹出输入框，并提示用户输入任务编号
        taskCode = ''
        taskCode = prompt('请输入任务编号');

        // 检查用户是否输入了任务编号
        if (taskCode !== null && taskCode !== "") {
          // 如果用户输入了任务编号，可以在这里处理任务编号
          alert('您输入的任务编号是：' + taskCode);
          document.getElementById('mode-info').innerText = '当前扫描模式为：到件扫描，任务编号：' + taskCode;
        } else {
          // 如果用户没有输入任务编号，提示用户重新输入
          alert('任务编号不能为空，请重新输入。');
        }
      }
      if (mode == 6) {
        document.getElementById('mode-info').innerText = '当前扫描模式为：' + "派件扫描"
      }
      if (mode == 7) {
        document.getElementById('mode-info').innerText = '当前扫描模式为：' + "签收扫描"
      }

      // 这里可以添加根据选择的扫描类型加载不同数据的逻辑
    });
  </script>
  <div class="footer">
    <div class="foo_main">
      <div id="additional-info"></div>
    </div>
  </div>
</body>

</html>